package com.attendance.sz;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.attendance.sz.utils.ClsPublic;
import com.attendance.sz.utils.MyApplication;
import com.attendance.sz.utils.Session;
import com.attendance.sz.utils.ZipExtractorTask;
import com.attendance.sz.utils.logMa;
import com.yc.card.utils.Licence;
import com.yc.card.utils.Nfc;
import com.yc.nfc.Convert;

import java.io.File;
import java.io.IOException;
import java.net.URL;


public class Splash extends BaseNewActivity {

    private final int SPLASH_DISPLAY_LENGHT = 3000;
    private static final String LOGTAG = "martrin";
    Context myContext;
    WindowManager manager;

    RelativeLayout rlRemind;
    RelativeLayout rl_background;
    TextView txtTitle;
    String androidId = null;
    String licencePath;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        licencePath = Environment.getExternalStorageDirectory().getPath() + "/licencecard.dat";
        downLicence(licencePath);
        logMa.setDEBUGBREAK(true);//false);//true);//如果为假则dt起作用日志输出适用少量日志测试, 如果为真，则以前大量日志输出
        logMa.d(LOGTAG, "Startd...");
        logMa.dt(LOGTAG, "Startdt...");
        // if (GetVersion.GetSystemVersion() > 2.3)
        if (android.os.Build.VERSION.SDK_INT > 2.3) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads().detectDiskWrites().detectNetwork()
                    .penaltyLog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
                    .build());
        }

        androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
        ((MyApplication) getApplication()).setAndroidid(androidId);//将唯一的设备号存起来

        if ((((MyApplication) getApplication()).getAndroidid()).equals("1972f51b3ae3fe5")) {
            ClsPublic.imyDeivceID = 0;////0--表示我的手机ANDROID设备
        }

		/*
		 * 日志部分
		 */
        (MyApplication.getApp()).setgVisibleLogWin(true);//false--不可见,true);//default
        if (Session.getLogTranFlag().equals("1")) {
            ((MyApplication) getApplication()).setDEBUGNET(true);// 通过网络输出
        } else {
            ((MyApplication) getApplication()).setDEBUGNET(false);// 不输出
        }
        ((MyApplication) getApplication()).setgstrDestIP(Session.getServerLogIp());
        ((MyApplication) getApplication()).setgiDestPort(Integer.valueOf(Session.getServerLogPort()));


        logMa.d(LOGTAG, ":" + "onCreate() of Splash=" + ((MyApplication) getApplication()).getAndroidid());//ID:1972f51b3ae3fe5
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);
        txtTitle = (TextView) findViewById(R.id.txttitle);
        txtTitle.setText(Session.getCompanyInfo());

        //This is a test!!!
        rl_background = (RelativeLayout) findViewById(R.id.rl_background);
        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备
            rl_background.setBackgroundResource(R.drawable.backori);
        }else{
            if("0".equals(Session.getVisibility())){
                rl_background.setBackgroundResource(R.drawable.back_empty);
            }else{
                rl_background.setBackgroundResource(R.drawable.back);
            }
        }

        String[] strDa = new String[7];

        /////////////////////////////////////////////////////////////////////////
        if (true) {
            myContext = this;
            manager = this.getWindowManager();

            rlRemind = (RelativeLayout) findViewById(R.id.rlRemind);
            final MyApplication theApp = (MyApplication) getApplication();//全局变量对
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.changedeviceno.receiver");
            registerReceiver(changedevicenoReceiver, filter);

//		if (Session.getDeviceNo().equals("0")) {
//			rlRemind.setVisibility(View.VISIBLE);//
//
//			Session.setCanReadCard("0");
//			Session.setCanInit("1");
//		} else {
            new AsynExcuteAction("CHECK_DOWNLOAD").execute();
//		}


        }
    }

    public class AsynExcuteAction extends AsyncTask<Void, Integer, Integer> {
        String actionType;

        public AsynExcuteAction(String actionType) {
            logMa.d(LOGTAG, ":" + actionType);
            this.actionType = actionType;
        }

        @Override
        protected void onPreExecute() {
            logMa.d(LOGTAG, ":" + "onPreExecute");
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Void... arg0) {
            try {
                logMa.d(LOGTAG, ":" + SPLASH_DISPLAY_LENGHT);
                Thread.sleep(SPLASH_DISPLAY_LENGHT);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return 0;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // manager.mProgress.setProgress(values[0]);
            logMa.d(LOGTAG, ":" + values);
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Integer resultValue) {
            Intent mainIntent = new Intent();
            mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            mainIntent.setClass(Splash.this, MainActivity.class);

            startActivity(mainIntent);
            finish();
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

            logMa.d(LOGTAG, ":" + resultValue);
            Session.setCanReadCard("1");
            Session.setCanInit("0");
        }

        @Override
        protected void onCancelled() {
            logMa.d(LOGTAG, ":" + "onCancelled");
        }
    }

    public BroadcastReceiver changedevicenoReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            logMa.d(LOGTAG, ":" + action);
            if (action.equals("com.changedeviceno.receiver")) {

                logMa.d(LOGTAG, ":" + "deviceNo="
                        + intent.getExtras().getString("p_deviceno"));
                Intent mainIntent = new Intent();
                mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mainIntent.setClass(Splash.this, MainActivity.class);

                startActivity(mainIntent);
                finish();
                overridePendingTransition(R.anim.push_left_in,
                        R.anim.push_left_out);

            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(changedevicenoReceiver);

        if (!Session.getDeviceNo().equals("0")) {
            android.os.Process.killProcess(android.os.Process.myPid());
        }

    }

    private void downLicence(final String licencePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File tempFile = new File(licencePath);
                    if (tempFile.exists()) {
                        tempFile.delete();
                    }
                    tempFile.createNewFile();
                  Log.d("licence",Session.getDownAdvUrl()+"/licencecard.dat");
                    URL url = new URL(Session.getDownAdvUrl()+"/licencecard.dat");
                    boolean downloaded = ZipExtractorTask.requestDownload(url, licencePath);
                    Licence licence = Nfc.getLicence(licencePath);
                    if (licence!=null){
                        byte key[] = licence.oprater_password;
                        int CardSection = licence.xfxt_sec;
                        Session.setCardSection(String.valueOf(CardSection+1));
                        byte[] mkey = new byte[6];
                        mkey[0] = key[0];
                        mkey[1] = key[1];
                        mkey[2] = key[2];
                        mkey[3] = key[3];
                        mkey[4] = key[4];
                        mkey[5] = key[5];
                        Session.setCardKey(Convert.ByteArrToHex(mkey).replace(" ",""));
                    }
                    if (downloaded) {
                    } else {
                        tempFile.delete();
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();

    }
}